package cn.xy.ymcc.mq.consumer;

import cn.xy.ymcc.domain.MessageEmail;
import cn.xy.ymcc.domain.User;
import cn.xy.ymcc.feign.SendMessageFeignClient;
import cn.xy.ymcc.util.EMailUtils;
import com.alibaba.fastjson.JSON;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.List;

@Component
@RocketMQMessageListener(
        consumerGroup = "service-common-emailmessage-consumer",
        topic = "messageEmail-topic",
        selectorExpression = "messageEmail-tags"
)
public class EmailMessageConsumer implements RocketMQListener<MessageExt> {
    @Autowired
    private SendMessageFeignClient sendMessageFeignClient;

    @Override
    public void onMessage(MessageExt message) {

        String bodyStr = new String(message.getBody(), StandardCharsets.UTF_8);
        MessageEmail messageEmail = JSON.parseObject(bodyStr, MessageEmail.class);
        //1.保持数据到数据库
        List<User> users = messageEmail.getUsers();
        for (User user : users) {
            messageEmail.setEmail(user.getEmail());
            messageEmail.setUserId(user.getId());
            messageEmail.setSendTime(new Date());
            sendMessageFeignClient.save(messageEmail);
        }
        //2.发送邮件
        EMailUtils.sendMail("2756150053@qq.com",messageEmail.getEmail(), messageEmail.getTitle(), messageEmail.getContent());
    }
}